package com.miquan.minotehelper.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * Created by mq on 2015/8/6.
 * --- 流弊 ---
 */
public class MySurfaceView extends SurfaceView
        implements SurfaceHolder.Callback, Runnable {
    //SurfaceView基本
    private SurfaceHolder sfh;//操控SurfaceView
    private Paint p;
    private Canvas c;
    //线程
    private Thread t;
    private boolean flag;
    //数据
    private int screenW, screenH;
    private int xx = 100, yy = 100;

    public MySurfaceView(Context context) {
        super(context);
        init();
    }

    public MySurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        sfh = this.getHolder();
        sfh.addCallback(this);
        p = new Paint();
        p.setColor(Color.RED);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        xx = (int) event.getX();
        yy = (int) event.getY();
        return true;
    }

    //游戏逻辑
    public void logic() {
    }

    public void myDraw() {
        try {
            //当SurfaceView不可编辑或尚未创建，会返回null
            c = sfh.lockCanvas();
            if (c != null) {
                c.drawColor(Color.GREEN);//刷屏
                c.drawText("me", xx, yy, p);//画
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (c != null) {
                sfh.unlockCanvasAndPost(c);
            }
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        screenW = this.getWidth();
        screenH = this.getHeight();
        //线程的初始化和启动都写在create里面
        flag = true;
        t = new Thread(this);
        t.start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        flag = false;
    }

    @Override
    public void run() {
        while (flag) {
            //刷屏时间保持一致
            //一般会在10~20帧左右
            //每秒20帧：1000ms/20=50ms每帧
            long start = System.currentTimeMillis();
            logic();
            myDraw();
            long end = System.currentTimeMillis();
            try {
                if (end - start < 50) {
                    Thread.sleep(50 - (end - start));
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
